/************************************************
 * Copyright (c) 2007 ~ 2009, 
 * All rights reserved.
 * Version   : 1.0
 * Author    : lengsh@alibaba-inc.com 
 * Date      : 2009.1.2
 ************************************************/

#ifndef   __HERON_POSTGRES_STORAGE_H___
#define   __HERON_POSTGRES_STORAGE_H___

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <syslog.h>
#include <signal.h>
#include <unistd.h>
#include "IStorage.h"
#include <viva.h>
#include <glib.h>
#include <libpq-fe.h>
using namespace std;
namespace heron {
class PostgreStorage : public  IStorage
{
	public:
		PostgreStorage(){
			m_pTx = NULL;
#ifdef   _THREAD_SAFE
			pthread_mutex_init(&_lock, NULL);
			DEBUG1("pthread_mutex_initi for TXlog");
#endif

		}
		virtual ~PostgreStorage(){
#ifdef  _THREAD_SAFE
			DEBUG1("pthread_mutex_destroy");
			pthread_mutex_destroy(&_lock);
#endif
		}
		virtual bool Initialize(const char *conf) ;
		virtual int Write(int ihash, const char *uid, const char *dm, const char *key, const char *val, const char *opt = HERON_CMD_REPLACE) ;
		virtual int Read(int ihash, const char *uid, const char *dm, const char *key, string &val);
		virtual int Write(int ihash, const char *uid, const char *dm, GHashTable *kv, const char *opt = HERON_CMD_REPLACE);
		virtual int Read(int ihash, const char *uid, const char *dm, GList *rkv, GHashTable *kv);
		virtual int Dump(int ihash, const char *uid, const char *dm, GHashTable *kv);

		virtual int Create(int ihash, const char *uid, const char *dm, GHashTable *kv);
		virtual int UUID(int ihash, const char *uid);
	protected:
		Viva *m_pTx;
		bool m_bWrite2DB;
		int read_user_value(PGconn *conn, int ihash, const char *uid, const char *dm, GList *rkv, GHashTable *kv);
		bool read_user_value(PGconn *conn, int ihash, const char *uid, const char *dm, const char *key, string &val);
		int dump_user_value(PGconn *conn, int ihash, const char *uid, const char *dm, GHashTable *kv);

		int write_db(int ihash, const char *uid, const char *dm, const char *key, const char *val, const char *stime, const char *opt = HERON_CMD_REPLACE) ;
		int write_viva(const char *uid, const char *dm, const char *key, const char *val, const char *stime, const char *opt = HERON_CMD_REPLACE) ;
		int write_db(int ihash, const char *uid, const char *dm, GHashTable *kv,const char *stime, const char *opt = HERON_CMD_REPLACE);
		int write_viva(const char *uid, const char *dm, GHashTable *kv,const char *stime, const char *opt = HERON_CMD_REPLACE);
		int create_db(int ihash, const char *uid, const char *dm, const char *val, const char * stime);
		int create_viva(const char *uid, const char *dm, const char *val, const char *stime);

#ifdef  _THREAD_SAFE
                pthread_mutex_t _lock;
#endif

};

}

#endif  // __HERON_POSTGRES_STORAGE_H___
